package com.lyn.seckill.controller;

import com.lyn.seckill.common.ResponseReturnType;
import com.lyn.seckill.common.error.BusinessException;
import com.lyn.seckill.common.error.EnumBusinessError;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class BaseController {

    public static final String CONTENT_TYPE_FORMED="application/x-www-form-urlencoded;charset=utf-8";
    public static final String CONTENT_TYPE_JSON="application/jason;charset=utf-8";

    /**
     * 异常处理
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handleException(HttpServletRequest request, Exception exception) {
        Map<String, Object> responseData = new HashMap<>();
        if (exception instanceof BusinessException) {
            BusinessException be = (BusinessException) exception;
            responseData.put("errorCode", be.getErrorCode());
            responseData.put("errorMessage", be.getErrorMessage());
        } else {
            responseData.put("errorCode", EnumBusinessError.UNKNOWN_ERROR.getErrorCode());
            responseData.put("errorMessage", EnumBusinessError.UNKNOWN_ERROR.getErrorMessage());
        }
        return ResponseReturnType.create(responseData,"fail");
    }
}
